#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);

    m_tcpBlockSize = 0;
    m_tcpSocket = new QTcpSocket(this);

    connect(m_tcpSocket, SIGNAL(readyRead()),
            this, SLOT(readyToRead()));

    m_tcpSocket->connectToHost("localhost", 55555);

}

Client::~Client()
{
    delete ui;
}

QByteArray buff;

void Client::readyToRead(void)
{
    QByteArray ba = m_tcpSocket->readAll();
    qDebug() << "Client::readyToRead: " << ba.size();
    if(ba.size() == 65536)
    {
        buff.append(ba);
    }else
    {
        buff.append(ba);
        qDebug() << "RecvImage: " << buff.size();

        QDataStream in(&buff, QIODevice::ReadOnly);
        in.setVersion(QDataStream::Qt_4_6);

//        if(m_tcpBlockSize == 0)
//        {
//            if(m_tcpSocket->bytesAvailable()<sizeof(quint16))
//                return;
            in >> m_tcpBlockSize;
//        }

//        if(m_tcpSocket->bytesAvailable() < m_tcpBlockSize)
//            return;

        QImage img;
        in >> img;
        ui->label->setPixmap(QPixmap::fromImage(img));

        m_tcpBlockSize = 0;
        buff.clear();
    }
}

void Client::on_pb_send_clicked()
{
    QByteArray buffer;
    QDataStream out(&buffer, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);

//    QString greeting = QString("Hello! The time is %1")
//        .arg(QTime::currentTime().toString());
    out << (quint16)0;
    out << ui->le_message->text();
    out.device()->seek(0);
    out << (quint16)(buffer.size() - sizeof(quint16));

    m_tcpSocket->write(buffer);
}
